package com.yylending.las.lending.outlet;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.Global;
import com.yylending.las.R;
import com.yylending.las.StatIDSet;
import com.yylending.las.YJKD;
import com.yylending.las.base.BaseActivity;
import com.yylending.las.common.widgets.CommonDialog;

/**
 * 门店页面-查看门店地址、联系方式
 * Created by laixj on 2017/11/4.
 * Copyright ©2017 www.yylending.com. All Rights Reserved.
 */

public class OutletActivity extends BaseActivity implements OutletPresenter.View, PopupWindow.OnDismissListener {
	public static final String TAG = OutletActivity.class.getSimpleName();

	private static final String KEY_OUTLET = "OUTLET";

	private static final int LOADER_ID_OUTLET = 1;
	/**
	 * 百度地图包名
	 */
	public static final String BAIDU_PACK_NAME = "com.baidu.BaiduMap";
	/**
	 * 高德地图包名
	 */
	public static final String GAODE_PACK_NAME = "com.autonavi.minimap";

	@BindView(R.id.map_view)
	MapView mMapView;
	@BindView(R.id.goto_outlet)
	Button mGotoOutlet;
	@BindView(R.id.outlet_hint)
	TextView mOutletHint;
	@BindView(R.id.outlet_contact)
	TextView mOutletContact;
	@BindView(R.id.outlet_address)
	TextView mOutletAddress;
	@BindView(R.id.no_network_layout)
	RelativeLayout mNoNetworkLayout;
	@BindView(R.id.outlet_info_rl)
	RelativeLayout mOutletInfoRl;

	private AMap aMap;

	private OutletPresenter mOutletPresenter;

	/**
	 * 门店信息
	 */
	private OutletModel.Outlet mOutlet;
	/**
	 * 门店地址信息
	 */
	private String address;
	private PopupWindow mPopupWindow;

	public static void start(Context context) {
		Intent starter = new Intent(context, OutletActivity.class);
		context.startActivity(starter);
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_OUTLET:
				mOutletPresenter = (OutletPresenter) data;
				mOutletPresenter.attach(this);
				mOutletPresenter.getOutletInfo();
				break;
			default:
				break;
		}
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_OUTLET:
				return new PresenterLoader<>(this, new OutletPresenter.Generator());
			default:
				return null;
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_outlet);
		ButterKnife.bind(this);
		mOutlet = (OutletModel.Outlet) getIntent().getSerializableExtra(KEY_OUTLET);
		setTitle(R.string.outlet_address);
		getSupportLoaderManager().initLoader(LOADER_ID_OUTLET, null, this);

		//高德地图初始化 必须调用onCreate 此方法必须重写
		mMapView.onCreate(savedInstanceState);
		aMap = mMapView.getMap();
		aMap.getUiSettings().setZoomControlsEnabled(false);
		//初始化定位蓝点样式类 myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);
		// 连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
		/*MyLocationStyle myLocationStyle = new MyLocationStyle();
		myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
		aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
		aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
		aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。*/
		StatService.onEvent(OutletActivity.this, StatIDSet.EVENT_ID_VIEW_OUTLET_MAP);
	}

	private void updateMap(OutletModel.Outlet outlet, double longitude, double latitude) {
		try {
			aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 19));
			MarkerOptions markerOption = new MarkerOptions();
			markerOption.position(new LatLng(latitude, longitude));
			markerOption.title(outlet.name);//.snippet(outlet.address);
			markerOption.draggable(true);
			markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
			Marker marker = aMap.addMarker(markerOption);
			marker.showInfoWindow();
		} catch (Exception e) {
			//showToast(R.string.get_location_latitude_and_longitude);
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		Global.setThirdPartyPageOpenedFlag(false);
	}

	@Override
	protected void onResume() {
		mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		mMapView.onDestroy();
		getSupportLoaderManager().destroyLoader(LOADER_ID_OUTLET);
		super.onDestroy();
	}

	@OnClick({R.id.goto_outlet, R.id.no_network_layout, R.id.outlet_contact})
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.goto_outlet:
				if (checkApkExist(OutletActivity.this, BAIDU_PACK_NAME) && checkApkExist(OutletActivity.this, GAODE_PACK_NAME)) {
					showPopupWindow();
				} else if (checkApkExist(OutletActivity.this, BAIDU_PACK_NAME)) {
					startNativeBaidu(this, mOutlet);
				} else if (checkApkExist(OutletActivity.this, GAODE_PACK_NAME)) {
					startNativeGaode(this, mOutlet);
				} else {
					startGaodeUrl(this, mOutlet);
					//showToast(R.string.map_app_not_exist);
				}
				break;
			case R.id.no_network_layout:
				mOutletPresenter.getOutletInfo();
				break;
			case R.id.outlet_contact:
				showTwoBtnDialog(mOutlet.phone, getString(R.string.call), getString(R.string.cancel), new CommonDialog.ButtonClickListener() {
					@Override
					public void onCancel(CommonDialog dialog) {
						dialog.dismiss();
					}

					@Override
					public void onConfirm(CommonDialog dialog) {
						dialog.dismiss();
						//忽略手势密码
						Global.setThirdPartyPageOpenedFlag(true);
						YJKD.tel(OutletActivity.this, mOutlet.phone.replaceAll("-", ""));
					}
				}, true);
				break;
			default:
				break;
		}
	}

	private void initSelectPopupWindow() {
		View view = View.inflate(this, R.layout.popup_window_select_map_app, null);
		view.findViewById(R.id.select_gaode_map).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mPopupWindow.dismiss();
				startNativeGaode(OutletActivity.this, mOutlet);
			}
		});
		view.findViewById(R.id.select_baidu_map).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mPopupWindow.dismiss();
				startNativeBaidu(OutletActivity.this, mOutlet);
			}
		});
		view.findViewById(R.id.select_map_cancel).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mPopupWindow.dismiss();
			}
		});
		mPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
		mPopupWindow.setOutsideTouchable(true);
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		mPopupWindow.setFocusable(true);// 点击空白处时，隐藏掉pop窗口

		mPopupWindow.setOnDismissListener(this);
	}

	/**
	 * 设置添加屏幕的背景透明度
	 *
	 * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明
	 */
	public void setBackgroundAlpha(float bgAlpha) {
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.alpha = bgAlpha;
		getWindow().setAttributes(lp);
	}

	private void showPopupWindow() {
		if (null == mPopupWindow) {
			initSelectPopupWindow();
		}
		setBackgroundAlpha(0.5f);//设置屏幕透明度
		mPopupWindow.showAtLocation(mGotoOutlet, Gravity.BOTTOM, 0, 0);
	}

	/**
	 * 检查是否已安装某app
	 *
	 * @param context
	 * @param packageName
	 * @return
	 */
	public static boolean checkApkExist(Context context, String packageName) {
		if (TextUtils.isEmpty(packageName))
			return false;
		try {
			context.getPackageManager().getApplicationInfo(packageName, PackageManager.MATCH_UNINSTALLED_PACKAGES);
			return true;
		} catch (PackageManager.NameNotFoundException e) {
			return false;
		}
	}

	/**
	 * 打开百度地图导航
	 *
	 * @param context
	 * @param outlet
	 */
	public void startNativeBaidu(Context context, OutletModel.Outlet outlet) {
		if (outlet == null) {
			return;
		}
		//忽略手势密码
		Global.setThirdPartyPageOpenedFlag(true);
		try {
			Intent intent = new Intent();
			double[] position = gcj02_To_Bd09(Double.parseDouble(outlet.latitude), Double.parseDouble(outlet.longitude));
			CLog.i(TAG, "经度：" + position[1]);
			CLog.i(TAG, "纬度：" + position[0]);
			intent.setData(Uri.parse("baidumap://map/geocoder?src=openApiDemo&address=" + address));
			//intent.setData(Uri.parse("baidumap://map/marker?location="+position[0]+","+position[1]+"&title="+mOutlet.name+"&content="+mOutlet.address+"&traffic=on"));
			//intent.setData(Uri.parse("baidumap://map/navi?location="+outlet.latitude+","+outlet.longitude));
			context.startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
			showToast("地址解析错误");
		}
	}

	/**
	 * 打开高德地图导航
	 *
	 * @param context
	 * @param outlet
	 */
	public void startNativeGaode(Context context, OutletModel.Outlet outlet) {
		if (outlet == null) {
			return;
		}
		//忽略手势密码
		Global.setThirdPartyPageOpenedFlag(true);
		try {
			double[] position = bd09_To_Gcj02(Double.parseDouble(outlet.latitude), Double.parseDouble(outlet.longitude));
			CLog.i(TAG, "经度：" + position[1]);
			CLog.i(TAG, "纬度：" + position[0]);
			Intent intent = new Intent("android.intent.action.VIEW",
					Uri.parse("androidamap://viewMap?sourceApplication=" + getString(R.string.app_name) + "&poiname=" + outlet.address + "&lat=" + Double.toString(position[0]) + "&lon=" + Double.toString(position[1]) + "&dev=0"));
			intent.setPackage("com.autonavi.minimap");
			context.startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
			showToast("地址解析错误");
		}
	}

	/**
	 * 在浏览器中打开高德地图导航
	 *
	 * @param context
	 * @param outlet
	 */
	private void startGaodeUrl(Context context, OutletModel.Outlet outlet) {
		//忽略手势密码
		Global.setThirdPartyPageOpenedFlag(true);
		double[] position = bd09_To_Gcj02(Double.parseDouble(outlet.latitude), Double.parseDouble(outlet.longitude));
		CLog.i(TAG, "经度：" + position[1]);
		CLog.i(TAG, "纬度：" + position[0]);
		String url = "http://uri.amap.com/marker?position=" + Double.toString(position[1]) + "," + Double.toString(position[0]) + "&name=" + outlet.address + "&src=" + getString(R.string.app_name) + "&coordinate=gaode&callnative=0";
		Intent intent = new Intent();
		intent.setAction("android.intent.action.VIEW");
		Uri content_url = Uri.parse(url);
		intent.setData(content_url);
		startActivity(intent);
	}

	/**
	 * 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换算法 将 GCJ-02 坐标转换成 BD-09 坐标
	 *
	 * @param lat
	 * @param lon
	 * @return
	 */
	public static double[] gcj02_To_Bd09(double lat, double lon) {
		double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
		double x = lon, y = lat;
		double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
		double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
		double tempLon = z * Math.cos(theta) + 0.0065;
		double tempLat = z * Math.sin(theta) + 0.006;
		double[] gps = {tempLat, tempLon};
		return gps;
	}

	/**
	 * 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换算法 将 BD-09 坐标转换成GCJ-02 坐标
	 *
	 * @param lat
	 * @param lon
	 * @return
	 */
	public static double[] bd09_To_Gcj02(double lat, double lon) {
		double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
		double x = lon - 0.0065, y = lat - 0.006;
		double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
		double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
		double tempLon = z * Math.cos(theta);
		double tempLat = z * Math.sin(theta);
		double[] gps = {tempLat, tempLon};
		return gps;
	}

	@Override
	public void getOutletInfoSuccess(OutletModel.Outlet outlet) {
		mOutlet = outlet;
		showReloadView(View.GONE);
		showOutletInfo();
	}

	@Override
	public void getOutletInfoFailure(String tips) {
		showToast(R.string.get_outlet_info_fail);
		finish();
	}

	private void showOutletInfo() {
		mMapView.setVisibility(View.VISIBLE);
		mOutletInfoRl.setVisibility(View.VISIBLE);
		mGotoOutlet.setVisibility(View.VISIBLE);
		double[] position = bd09_To_Gcj02(Double.parseDouble(mOutlet.latitude), Double.parseDouble(mOutlet.longitude));
		CLog.i(TAG, "经度：" + position[1]);
		CLog.i(TAG, "纬度：" + position[0]);
		updateMap(mOutlet, position[1], position[0]);
		mOutletAddress.setText(mOutlet.address);
		mOutletContact.setText(mOutlet.phone);
		if (mOutlet.address.contains(mOutlet.city)) {
			address = mOutlet.address;
		} else {
			address = mOutlet.city + mOutlet.address;
		}
	}

	private void showReloadView(int visible) {
		if ((visible == View.GONE && mNoNetworkLayout.getVisibility() == View.VISIBLE)
				|| (visible == View.VISIBLE && mNoNetworkLayout.getVisibility() == View.GONE)) {
			mNoNetworkLayout.setVisibility(visible);
		}
	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips, int functionalCode) {
		super.onFunctionalError(e, autoTips, functionalCode);
		switch (functionalCode) {
			case OutletModel.FUNCTION_CODE_GET_OUTLET_LIST:
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						showReloadView(View.VISIBLE);
					}
				});
				break;
		}
	}

	@Override
	public void onDismiss() {
		setBackgroundAlpha(1.0f);//设置屏幕透明度
	}
}
